const express = require("express");
const pool = require("../pool.js");
//使用理由器
var router = express.Router();
//增加
router.post("/add",(req,res)=>{
  var obj = req.body;
  var sql = "insert into possible_like set ?"
	pool.query(sql,obj,(err,result)=>{
		if(err) throw err;
		if (result.affectedRows > 0){
			res.send({
				"code":200,
				"msg":"添加成功"
			});
		}else{
			res.send({
				"code":301,
				"msg":"添加失败"
			});
		}
	})
})
//获取分页路由
router.get("/list", (req, res) => {
  var obj = req.query;
  var _page = obj.page;
  var _size = obj.size;
  if (!_page) {
    _page = 1;
  }
  if (!_size) {
    _size = 10;
  }
  //计算从第几条数据开始
  _page = (_page - 1) * _size;
  //把字符串转化为整数
  _page = parseInt(_page);
  _size = parseInt(_size);

  var sql = "SELECT * FROM possible_like LIMIT ?,?";
  pool.query(sql, [_page, _size], (err, result) => {
    if (err) throw err;
    res.send(result);
  });
});
//删除
router.get("/delete", (req, res) => {
  var _lid = req.query.lid;
  var sql = "DELETE FROM possible_like WHERE lid=?";
  pool.query(sql, _lid, (err, result) => {
    if (err) throw err;
    if (result.affectedRows > 0) {
      res.send({
        "code": 200,
        "msg": "删除成功"
      });
    } else {
      res.send({
        "code": 301,
        "msg": "删除失败"
      });
    }
  })
})
//获取详情
router.get("/details", (req, res) => {
  var _lid = req.query.lid;
  var sql = "SELECT * FROM possible_like WHERE lid=?";
  pool.query(sql, _lid, (err, result) => {
    if (err) throw err;
    if (result.length) {
      res.send(result);
    } else {
      res.send({
        "code": 301,
        "msg": "查询失败"
      })
    }
  })
})
//编辑
router.post("/update", (req, res) => {
  var obj = req.body;
  for (var key in obj) {
    if (!obj[key]) {
      res.send({
        "code": 301,
        "msg": key + "不能为空"
      })
      return;
    }
  }
  var _lid = obj.lid;
  delete obj.lid;
  var sql = "UPDATE possible_like SET ? WHERE lid=?";
  pool.query(sql, [obj, _lid], (err, result) => {
    if (err) throw err;
    if (result.affectedRows > 0) {
      res.send({
        "code": 200,
        "msg": "修改成功"
      })
    } else {
      res.send({
        "code": 301,
        "msg": "修改失败"
      })
    }
  })
})
//导出路由器
module.exports = router;
